package game;

import static game.Settings.getColumns;
import static game.Settings.getLines;
import static game.Settings.readFromFile;

import java.util.concurrent.CountDownLatch;

public class Game {

	private static final int NUMBER_OF_PLAYERS = 4;
	// Latch used to ensure that none of the Players start until all of them are
	// ready to start
	private static final CountDownLatch startOfGame = new CountDownLatch(1);
	// Latch used to indicate the end of game: the first Player who finishes the
	// game calls countDown, and than all the other threads are interrupted by
	// the main thread
	private static final CountDownLatch endOfGame = new CountDownLatch(1);
	private static Player[] players = new Player[NUMBER_OF_PLAYERS];
	private static int playerNumber;

	public static void main(String[] args) {
		readFromFile();
		int lines = getLines();
		int columns = getColumns();
		int x = 0, y = 0;
		for (playerNumber = 0; playerNumber < NUMBER_OF_PLAYERS; playerNumber++) {
			switch (playerNumber) {
			case 0:
				x = 0;
				y = 0;
				break;
			case 1:
				x = 0;
				y = columns - 1;
				break;
			case 2:
				x = lines - 1;
				y = 0;
				break;
			case 3:
				x = lines - 1;
				y = columns - 1;
				break;
			}
			players[playerNumber] = new Player(playerNumber + 1, x, y,
					endOfGame);
			Thread currentThread = new Thread() {
				private int internalNumber = playerNumber;

				public void run() {
					try {
						startOfGame.await();
						players[internalNumber].start();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			currentThread.start();
		}
		startOfGame.countDown();
		try {
			endOfGame.await();
			for (playerNumber = 0; playerNumber < NUMBER_OF_PLAYERS; playerNumber++) {
				players[playerNumber].interrupt();
			}
			for (playerNumber = 0; playerNumber < NUMBER_OF_PLAYERS; playerNumber++) {
				players[playerNumber].join();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
